﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.DataInterfaces;
using MovieRental.EfRepositoryLibrary.Mappers;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.EfRepositoryLibrary
{
    public class EfEditionRepository : EfRepository<EditionInfo, Guid, Edition, Edition>, IEditionRepository
    {
        public EfEditionRepository(string connectionString)
            : base(connectionString)
        {
            _mapper = new EditionMapper();
        }

        public override void Delete(Guid id)
        {
            using (var context = CreateContext())
            {
                foreach (var loan in context.Loans)
                    loan.EditionId = null;
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't delete object from the database.", ex);
                }

            }
            base.Delete(id);
        }

        public IEnumerable<EditionInfo> LoadAllForMovie(Guid movieId)
        {
            using (var context = CreateContext())
            {
                try
                {
                    return context.Editions.Where(x => x.MovieId == movieId).ToList().Select(x => _mapper.ConvertBack(x));
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't load objects from the db.", ex);
                }
            }
        }
    }
}
